from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from backend.models import Match
import json


# 赛事新增接口
@csrf_exempt
@require_http_methods(['POST'])
def match_add(request):
    response = {}
    try:
        form = json.loads(request.body)['form']
        print(form)
        print(type(form))
        Match.objects.create(match_name=form['match_name'], match_img=form['match_img'], match_desc=form['match_desc'],
                             match_time=form['match_time'], application_time=form['application_time'])
        response['respMsg'] = 'success'
        response['respCode'] = '000000'
    except Exception as e:
        response['respMsg'] = str(e)
        response['respCode'] = '999999'
    return JsonResponse(response)


# 赛事查询接口
@csrf_exempt
@require_http_methods(['GET'])
def match_info(request):
    response = {}
    try:
        match_name = request.GET.get('match_name')
        cid = request.GET.get('id')
        if match_name:
            info = Match.objects.filter(match_name__contains=match_name)
        elif cid:
            info = Match.objects.filter(id=cid)
        else:
            info = Match.objects.all()
        response['respCode'] = '000000'
        response['respMsg'] = 'success'
        response['list'] = list(info.values())
    except Exception as e:
        response['respCode'] = '999999'
        response['respMsg'] = str(e)
    return JsonResponse(response)


#赛事删除接口
@csrf_exempt
@require_http_methods(['GET'])
def match_del(request):
    response = {}
    try:
        cid = request.GET.get('id')
        Match.objects.filter(id=cid).delete()
        response['respCode'] = '000000'
        response['respMsg'] = 'success'
    except Exception as e:
        response['respCode'] = '999999'
        response['respMsg'] = str(e)
    return JsonResponse(response)


# 编辑按钮
@csrf_exempt
@require_http_methods(['POST'])
def match_edit(request):
    response = {}
    try:
        form = json.loads(request.body)
        Match.objects.filter(id=form['id']).update(match_name=form['match_name'], match_img=form['match_img'], match_desc=form['match_desc'],
                             match_time=form['match_time'], application_time=form['application_time'])
        response['respMsg'] = 'success'
        response['respCode'] = '000000'
    except Exception as e:
        response['respMsg'] = str(e)
        response['respCode'] = '999999'
    return JsonResponse(response)